package org.ne.springboot.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.annotations.Select;
import org.ne.springboot.mapper.ArticleMapper;
import org.ne.springboot.pojo.Article;
import org.ne.springboot.pojo.Category;
import org.ne.springboot.pojo.PageBean;
import org.ne.springboot.service.ArticleService;
import org.ne.springboot.utils.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @author wey
 * @Date 2025/1/2 下午8:51 1月
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void add(Article article) {
        Map<String, Object> info = ThreadLocalUtils.get();
        int userId = Integer.parseInt((String) info.get("userId"));

        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        article.setCreateUser(userId);

        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, String categoryId, String state) {
        PageBean<Article> pageBean = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);

        Map<String, Object> map = ThreadLocalUtils.get();
        Integer userId = Integer.parseInt((String) map.get("userId"));

        List<Article> as = articleMapper.list(userId, categoryId, state);

        Page<Article> page = (Page<Article>) as;
        pageBean.setTotal(page.getTotal());
        pageBean.setItems(page.getResult());

        return pageBean;
    }

    @Override
    public void deleteById(Integer id) {
        articleMapper.delete(id);
    }

    @Override
    public Article findById(Integer id) {
        Map<String, Object> info = ThreadLocalUtils.get();
        int userId = Integer.parseInt((String) info.get("userId"));
        return articleMapper.findById(id, userId);

    }

    @Override
    public void update(Article article) {
        article.setUpdateTime(LocalDateTime.now());

        articleMapper.update(article);

    }
}
